//
//  ZXsaleChanceVIewController.m
//  qianke
//
//  Created by ZX on 2017/7/8.
//  Copyright © 2017年 ZX. All rights reserved.
//

#import "ZXsaleChanceVIewController.h"
#import "myTableViewCell.h"
#import "ZXCustomerModel.h"
#import "ZXsaleactivity2Cell.h"
#import "AddSaleActivityViewController.h"
#import "ZXSaleActivityController.h"
#import "ZXAddSaleActivityController.h"
@interface ZXsaleChanceVIewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
/*ilstArr*/
@property(copy ,nonatomic)NSMutableArray*listArr;
@property(copy ,nonatomic)NSMutableArray*thisMouthArr;
@property(copy ,nonatomic)NSMutableArray*tlastMouthArr;

@property(assign ,nonatomic)BOOL isRefersh;
@property(assign ,nonatomic)int pageNo;
@property(copy ,nonatomic)NSString * Count;
@property(assign ,nonatomic)int pageSize;
@property(assign ,nonatomic)int upLoadNumber;
@property (weak, nonatomic) IBOutlet UIButton *leftBtn;
@property (weak, nonatomic) IBOutlet UIButton *rightBtn;
@property (weak, nonatomic) IBOutlet UIView *btnBigView;
@property (weak, nonatomic) IBOutlet UIView *emptyView;
/*_NoMoreData*/
@property(assign ,nonatomic)BOOL NoMoreData;
@property(assign ,nonatomic)BOOL NoMoreDataRight;
@property(assign ,nonatomic)int page;

@end

@implementation ZXsaleChanceVIewController
@synthesize myTableView;

- (void)viewDidLoad {
    [super viewDidLoad];
    _isRefersh = NO;
    _pageSize = 10;
    _pageNo = 2;
    _page = 0;
    _rightConstaint.constant = ZXtableViewMargin;
    _leftConstaint.constant = ZXtableViewMargin;
    NSLogfun;
    self.view.backgroundColor = baseBackgroundColor;
    if (_type) {
        [_leftBtn setBackgroundColor:baseBlueColor];
        [_leftBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_rightBtn setBackgroundColor:[UIColor whiteColor]];
        [_rightBtn setTitleColor:baseBlueColor forState:UIControlStateNormal];
    }else{
        [_rightBtn setBackgroundColor:baseBlueColor];
        [_rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_leftBtn setBackgroundColor:[UIColor whiteColor]];
        [_leftBtn setTitleColor:baseBlueColor forState:UIControlStateNormal];
    }
    if (!_listArr) {
        _listArr =[[NSMutableArray alloc]init];
    }
    if (!_thisMouthArr) {
        _thisMouthArr =[[NSMutableArray alloc]init];
    }if (!_tlastMouthArr) {
        _tlastMouthArr =[[NSMutableArray alloc]init];
    }
    if (_type) {
        [self thisMounthData];
    }else {
        [self lastMounthData];
    }
    [self creatTableView];
    myTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"刷新");
        _isRefersh = YES;
        my_AppDelegate.isShow = YES;
        if (_type) {
            [self thisMounthData];
        }else {
            [self lastMounthData];
        }
    }];
    myTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
    
//    NSString * str = [ZXToolObj getMonthBeginWith:@"2017-9"];
//    NSString * str = [ZXToolObj getMonth];
//    NSLog(@"%@",str);
    [self layout];
}
-(void)viewWillAppear:(BOOL)animated{
    [self loadData];
    _page++;
//    if (_type) {
//        [self thisMounthData];
//    }else {
//        [self lastMounthData];
//    }
}
-(void)viewWillDisappear:(BOOL)animated{
    my_AppDelegate.isShow = NO;
}
-(void)layout{
    UIBezierPath *maskPath=[UIBezierPath bezierPathWithRoundedRect:_rightBtn.bounds byRoundingCorners:UIRectCornerTopRight|UIRectCornerBottomRight cornerRadii:CGSizeMake(5, 5)];
    CAShapeLayer *maskLayer=[[CAShapeLayer alloc]init];
    maskLayer.frame=_rightBtn.bounds;
    maskLayer.path=maskPath.CGPath;
    _rightBtn.layer.mask=maskLayer;
    _btnBigView.layer.borderWidth = 1;
    _btnBigView.layer.borderColor = baseBlueColor.CGColor;
    _btnBigView.layer.cornerRadius = 6;
    
    UIBezierPath *maskPath2=[UIBezierPath bezierPathWithRoundedRect:_leftBtn.bounds byRoundingCorners:UIRectCornerTopLeft|UIRectCornerBottomLeft cornerRadii:CGSizeMake(5, 5)];
    CAShapeLayer *maskLayer2=[[CAShapeLayer alloc]init];
    maskLayer2.frame=_leftBtn.bounds;
    maskLayer2.path=maskPath2.CGPath;
    _leftBtn.layer.mask=maskLayer2;
    
  
}
-(void)thisMounthData{
    _emptyView.hidden = YES;
    NSString * beginTim = [ZXToolObj getMonthBeginWith:[NSString stringWithFormat:@"2017-%@",[ZXToolObj getMonth]]];
    NSString * endTim = [ZXToolObj getMonthEndWith:[NSString stringWithFormat:@"2017-%@",[ZXToolObj getMonth]]];
    _beginTim = [NSString stringWithFormat:@"%@",beginTim];
    _endTim = [NSString stringWithFormat:@"%@",endTim];
//    if (_page<2) {
        if (!_isRefersh) {
            if (_thisMouthArr.count==0) {
                [self loadData];
            }else{
                [_listArr removeAllObjects];
                _listArr = [_thisMouthArr mutableCopy];
                [self.myTableView reloadData];
            }
        }else{
            [self loadData];
        }

    [self.myTableView reloadData];
}
-(void)lastMounthData{
    _emptyView.hidden = YES;
    NSString * beginTim = [ZXToolObj getMonthBeginWith:[NSString stringWithFormat:@"2017-%@",[ZXToolObj getLastMonth]]];
    NSString * endTim = [ZXToolObj getMonthEndWith:[NSString stringWithFormat:@"2017-%@",[ZXToolObj getLastMonth]]];
    _beginTim = [NSString stringWithFormat:@"%@",beginTim];
    _endTim = [NSString stringWithFormat:@"%@",endTim];
//    if (_page<2) {
    
        if (!_isRefersh) {
            if (_tlastMouthArr.count==0) {
                [self loadData];
            }else{
                [_listArr removeAllObjects];
                _listArr = [_tlastMouthArr mutableCopy];
                [self.myTableView reloadData];
            }
        }else{
            [self loadData];
        }
//    }else{
//        [self loadData];
//    }
}
-(void)loadMoreData{
    my_AppDelegate.isShow = YES;
    if (_Count.intValue%_pageSize) {
        _upLoadNumber = _Count.intValue/_pageSize + 1;
    }else _upLoadNumber = _Count.intValue/_pageSize;
    
    NSString *strURL = [NSString stringWithFormat:@"%@scrmForApp/ideaGuest/%d/%d?uid=%@&userName=%@&startTime=%@&endTime=%@",ZXBaseURL,_pageNo,_pageSize,my_AppDelegate.uid,my_AppDelegate.userName,_beginTim,_endTim];
    NSLog(@"strURL==%@",strURL);
    strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:strURL];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
    NSMutableURLRequest *mutableRequest = [request mutableCopy];
    [mutableRequest addValue:my_AppDelegate.access_token forHTTPHeaderField:accessTokenKey];
    request = [mutableRequest copy];
 
    NSLog(@"_pageNo==%d_upLoadNumber==%d",_pageNo,_upLoadNumber);
    [HTTPHelper GetHeadmutableRequest:request success:^(NSDictionary *data) {
//        NSLog(@"%@",data);
        NSLog(@"%@",[data objectForKey:@"message"]);
        NSString * string = [data objectForKey:@"message"];
        NSArray * arr = [data objectForKey:@"data"];
        NSString * msgCod = [data objectForKey:@"msgCod"];
    
        if ([string containsString:@"无数据" ]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [myTableView.mj_footer endRefreshing];
                [myTableView.mj_footer setState:MJRefreshStateNoMoreData];
                myTableView.mj_footer.hidden = YES;
            });
            return ;
        }
        if (![msgCod isEqualToString:@"S0001"]) {
            _pageNo++;
        }else{
            _NoMoreData = YES;
            [myTableView.mj_footer setState:MJRefreshStateNoMoreData];
            return ;
        }
        if (arr&&![arr isEqual:[NSNull null]]) {
            
        
        [_listArr removeAllObjects];
        for (NSDictionary * dic in arr) {
            ZXCustomerModel * model = [ZXCustomerModel new];
            if (dic&&![dic isEqual:[NSNull null]]){
                [model setValuesForKeysWithDictionary:dic];
            }
            [_listArr addObject:model];
        }
        NSLog(@"listArr.count==%lu",(unsigned long)_listArr.count);

        if (_type) {
            for (ZXCustomerModel * model in _listArr) {

                [_thisMouthArr addObject:model];
            }
            _listArr =[_thisMouthArr mutableCopy];
        }else {
            for (ZXCustomerModel * model in _listArr) {
                
                [_tlastMouthArr addObject:model];
            }
            _listArr = [_tlastMouthArr mutableCopy];
        }
        NSLog(@"listArr.count==%lu",(unsigned long)_listArr.count);
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [myTableView reloadData];
        });
        [myTableView.mj_footer endRefreshing];
    } failure:^(NSError *error) {
        [myTableView.mj_footer endRefreshing];
    }];
}

-(void)loadData{
    myTableView.mj_footer.hidden = NO;
    _emptyView.hidden = NO;
    NSString *strURL = [NSString stringWithFormat:@"%@scrmForApp/ideaGuest/1/10?uid=%@&userName=%@&startTime=%@&endTime=%@",ZXBaseURL,my_AppDelegate.uid,my_AppDelegate.userName,_beginTim,_endTim];
    NSLog(@"strURL==%@",strURL);
    strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:strURL];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
    NSMutableURLRequest *mutableRequest = [request mutableCopy];
    [mutableRequest addValue:my_AppDelegate.access_token forHTTPHeaderField:accessTokenKey];
    request = [mutableRequest copy];
    [_listArr removeAllObjects];
    [myTableView reloadData];
    [HTTPHelper GetHeadmutableRequest:request success:^(NSDictionary *data) {
        NSLog(@"%@",data);
        NSLog(@"%@",[data objectForKey:@"message"]);
        if (data) {
            NSArray * arr = [data objectForKey:@"data"];
            if (![arr isEqual:[NSNull null]]&&arr) {
                [_listArr removeAllObjects];
                for (NSDictionary * dic in arr) {
                    ZXCustomerModel * model = [ZXCustomerModel new];
                    if (dic&&![dic isEqual:[NSNull null]]){
                        [model setValuesForKeysWithDictionary:dic];
                    }
                    [_listArr addObject:model];
                }
                if (arr&&![arr isEqual:[NSNull null]]) {
                    if (arr.count<10) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            myTableView.mj_footer.hidden = YES;
                        });
                    }
                }
                NSLog(@"listArr==%@",_listArr);
                NSLog(@"listArr==%lu",(unsigned long)_listArr.count);
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    myTableView.mj_footer.hidden = YES;
                });
            }
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                    myTableView.mj_footer.hidden = YES;
            });
        }
        if (_type) {
            _thisMouthArr =[_listArr mutableCopy];
        }else {
            _tlastMouthArr = [_listArr mutableCopy];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [myTableView reloadData];
            if (_listArr.count>0) {
                _emptyView.hidden = YES;
            }else{
                
            }
            [myTableView.mj_header endRefreshing];
        });
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"请重试"];
        [myTableView.mj_header endRefreshing];
    }];
    
}
#pragma mark --tableview datasouse
-(void)creatTableView{
    myTableView.backgroundColor = [UIColor clearColor];
    myTableView.separatorStyle = NO;
    [self.view addSubview:myTableView];
    [myTableView registerNib:[UINib nibWithNibName:NSStringFromClass([myTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"cell"];
    myTableView.delegate = self;
    myTableView.dataSource = self;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_listArr.count>0) {
        return _listArr.count+1;
    }else{
        return _listArr.count;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == _listArr.count) {
        ZXsaleactivity2Cell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"ZXsaleactivity2Cell" owner:nil options:nil] firstObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.contentLabel.text = @"以上是最近销售机会记录";
        cell.backgroundColor = baseBackgroundColor;
        return cell;
    }
//    myTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    myTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"myTableViewCell" owner:nil options:nil] firstObject];
    }
    
   
    ZXCustomerModel * model = _listArr[indexPath.row];
    cell.status = model;
    cell.itTurnLabel.text = @"未转订单";
    cell.itTurnLabel.hidden = NO;
    cell.isTurnLabel1.hidden = NO;
    if (model.guestOrderId.intValue != 0) {
        cell.userInteractionEnabled = NO;
        cell.temView.hidden = NO;
        cell.itTurnLabel.text = @"已转订单";
    }
    cell.layer.cornerRadius = 5;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == _listArr.count) {
        return 33;
    }
    ZXCustomerModel * model = _listArr[indexPath.row];
    int height1 = [model.address stringSizeWithMaxSize:CGSizeMake(ScreenWidth*2/3, ScreenHeight) withFont:textfont].height;
    return 166 +height1;
}

#pragma mark -- tableview delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.row == _listArr.count) {
        return;
    }
    myTableViewCell * cell =[tableView cellForRowAtIndexPath:indexPath];
    if (cell.guestOrderId.intValue != 0) {
        return;
    }
    cell.userInteractionEnabled = NO;
//    if (cell.activityCount.intValue){
    ZXAddSaleActivityController * saleVc = [ZXAddSaleActivityController new];
    if (!saleVc.contentDic) {
        saleVc.contentDic = [NSMutableDictionary dictionary];
    }
    saleVc.noticeId = cell.noticeId;
    saleVc.chanceId = cell.noticeId;
    saleVc.fromType = YES;
    saleVc.sex = cell.sexLabel.text;
    saleVc.name = cell.nameLabel.text;
    saleVc.phone = cell.phoneLabel.text;
    saleVc.chexing = cell.carModelLabel.text;
    saleVc.xinghao = cell.ideaModelCode;
    saleVc.ideaColorName = cell.ideaColorName;
    saleVc.province = cell.province;
    saleVc.city = cell.city;
    saleVc.area = cell.area;
    saleVc.address = cell.address;
    saleVc.equipLevelCode = cell.equipLevelCode;
    saleVc.title = @"客户详情";
    saleVc.view.backgroundColor = baseBackgroundColor;
    saleVc.title = @"销售机会详情";
    [self.navigationController pushViewController:saleVc animated:YES];
    cell.userInteractionEnabled = YES;
//    }else{
//        AddSaleActivityViewController * saleVc = [AddSaleActivityViewController new];
//        saleVc.chanceId = cell.chanceId;
//        saleVc.title = @"添加销售活动";
//        saleVc.view.backgroundColor = baseBackgroundColor;
//        [self.navigationController pushViewController:saleVc animated:YES];
//    }

}
- (IBAction)leftBtnClick:(id)sender {
     [SVProgressHUD dismiss];
    _leftBtn.backgroundColor = baseBlueColor;
    _rightBtn.backgroundColor = [UIColor whiteColor];
    [_leftBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_rightBtn setTitleColor:baseBlueColor forState:UIControlStateNormal];
    _type = YES;
    _isRefersh = NO;
    [self thisMounthData];
}
- (IBAction)rightBtnClick:(id)sender {
     [SVProgressHUD dismiss];
    _rightBtn.backgroundColor = baseBlueColor;
    _leftBtn.backgroundColor = [UIColor whiteColor];
    [_rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_leftBtn setTitleColor:baseBlueColor forState:UIControlStateNormal];
    _type = NO;
    _isRefersh = NO;
    [self lastMounthData];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
